<?php
namespace App\Repository;
use App\Models\Base\Payment;

/**
 * 支付方式数据仓储类
 *
 * @package App\Http\Repository
 * @author WangBin
 * @mail: <849850352@qq.com>
 */
class PayRepository extends BaseRepository
{
    /**
     * 保存数据
     *
     * @param array $data
     * @param int $id
     * @throws
     * @return int|mixed
     */
    public function save(array $data, int $id = 0)
    {
        $query = $id ? Payment::query()->find($id) : new Payment();
        collect($data)->each(function ($value, $field) use ($query) {
            $query->{$field} = $value;
        });
        return $query->save() ? $query->pay_id : 0;
    }

    /**
     * 获取支付方式列表
     *
     * @param array $filter
     * @param array|string[] $column
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getList(array $filter = [], array $column = ['*'])
    {
        $query = Payment::query()->orderByDesc('created_at');
        if(!empty($filter['title'])) {
            $query->where('title', 'like', '%' . $filter['title'] . '%');
        }
        return $query;
    }

    /**
     * 根据支付方式 id 查询
     *
     * @param int $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getById(int $id)
    {
        return Payment::query()->where('pay_id', $id)->first();
    }

    /**
     * 检查支付 key 已存在
     *
     * @param string $key
     * @param int $id
     * @return bool
     */
    public function checkKeyExist(string $key, int $id = 0)
    {
        $query = Payment::query()->where('pay_key', $key);
        if($id) {
            $query->where('pay_id', '!=', $id);
        }
        return $query->exists();
    }
}
